import { NextRequest, NextResponse } from 'next/server';
import { Document, Paragraph, TextRun, HeadingLevel, Table, TableRow, TableCell, BorderStyle, WidthType, AlignmentType, ImageRun, Packer } from 'docx';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import UserModel from '@/models/user';

export async function GET(request: NextRequest) {
  try {
    // 检查请求头
    const authHeader = request.headers.get('authorization');
    console.log('Authorization header:', authHeader ? '存在' : '不存在');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      console.error('缺少Authorization头或格式不正确');
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const token = authHeader.split(' ')[1];
    console.log('Token:', token.substring(0, 20) + '...');

    // 尝试直接解析token
    try {
      // 尝试使用简化的方法解析token
      const tokenParts = token.split('.');
      if (tokenParts.length === 3) {
        try {
          const payload = JSON.parse(atob(tokenParts[1]));
          console.log('Token payload:', payload);

          if (payload && payload.id) {
            // 使用直接解析的用户ID
            const userId = payload.id;
            console.log('使用直接解析的用户ID:', userId);

            // 继续处理...
          } else {
            console.error('Token中没有用户ID');
            return NextResponse.json({ error: '无效的令牌' }, { status: 401 });
          }
        } catch (e) {
          console.error('JSON解析错误:', e);
        }
      }
    } catch (e) {
      console.error('Token解析错误:', e);
    }

    // 使用标准的authMiddleware
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      console.error('Auth failed:', authResult);
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取用户信息
    const user = await UserModel.findById(userId);
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 获取用户的教育经历、工作经历、技能等
    const educationExperiences = await UserModel.getEducationExperiences(userId);
    const workExperiences = await UserModel.getWorkExperiences(userId);
    const skills = await UserModel.getSkills(userId);

    // 尝试获取实习经历和获奖情况
    let internships = [];
    let awards = [];

    try {
      const [internshipsResult] = await UserModel.query<any[]>(
        'SELECT * FROM internships WHERE user_id = ? ORDER BY created_at DESC',
        [userId]
      );
      internships = Array.isArray(internshipsResult) ? internshipsResult : [];
    } catch (error) {
      console.error('获取实习经历失败:', error);
    }

    try {
      const [awardsResult] = await UserModel.query<any[]>(
        'SELECT * FROM awards WHERE user_id = ? ORDER BY date DESC',
        [userId]
      );
      awards = Array.isArray(awardsResult) ? awardsResult : [];
    } catch (error) {
      console.error('获取获奖情况失败:', error);
    }

    // 创建Word文档
    const doc = new Document({
      styles: {
        default: {
          document: {
            run: {
              font: "SimSun",
              size: 24,
            },
          },
        },
      },
      sections: [{
        properties: {},
        children: [
          // 标题
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [
              new TextRun({
                text: `${user.username} 的个人简历`,
                font: "SimSun",
                size: 32,
              }),
            ],
          }),

          // 个人信息
          new Paragraph({
            children: [
              new TextRun({
                text: '个人信息',
                font: "SimSun",
                size: 28,
              }),
            ],
            thematicBreak: true,
          }),

          // 表格
          new Table({
            width: {
              size: 100,
              type: WidthType.PERCENTAGE,
            },
            rows: [
              new TableRow({
                children: [
                  new TableCell({
                    children: [new Paragraph({
                      children: [new TextRun({ text: '姓名', font: "SimSun" })],
                    })],
                    width: { size: 20, type: WidthType.PERCENTAGE },
                  }),
                  new TableCell({
                    children: [new Paragraph({
                      children: [new TextRun({ text: user.username || '', font: "SimSun" })],
                    })],
                    width: { size: 30, type: WidthType.PERCENTAGE },
                  }),
                  new TableCell({
                    children: [new Paragraph('联系电话')],
                    width: {
                      size: 20,
                      type: WidthType.PERCENTAGE,
                    },
                  }),
                  new TableCell({
                    children: [new Paragraph(user.phone || '')],
                    width: {
                      size: 30,
                      type: WidthType.PERCENTAGE,
                    },
                  }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({
                    children: [new Paragraph('邮箱')],
                  }),
                  new TableCell({
                    children: [new Paragraph(user.email || '')],
                  }),
                  new TableCell({
                    children: [new Paragraph('所在地')],
                  }),
                  new TableCell({
                    children: [new Paragraph(user.location || '')],
                  }),
                ],
              }),
              new TableRow({
                children: [
                  new TableCell({
                    children: [new Paragraph('出生日期')],
                  }),
                  new TableCell({
                    children: [new Paragraph(user.birth_date ? new Date(user.birth_date).toLocaleDateString() : '')],
                  }),
                  new TableCell({
                    children: [new Paragraph('单位')],
                  }),
                  new TableCell({
                    children: [new Paragraph(user.company || '')],
                  }),
                ],
              }),
            ],
          }),

          // 教育经历标题
          new Paragraph({
            children: [
              new TextRun({
                text: '教育经历',
                font: "SimSun",
                size: 28,
              }),
            ],
            thematicBreak: true,
            spacing: { before: 400 },
          }),

          // 教育经历内容
          ...educationExperiences.map(edu => {
            return [
              new Paragraph({
                children: [
                  new TextRun({
                    text: `${edu.school} - ${edu.degree}${edu.field_of_study ? ` - ${edu.field_of_study}` : ''}`,
                    font: "SimSun",
                    size: 26,
                  }),
                ],
              }),
              new Paragraph({
                children: [
                  new TextRun({
                    text: `${edu.start_date ? new Date(edu.start_date).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' }) : ''} - ${edu.end_date ? new Date(edu.end_date).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' }) : '至今'}`,
                    font: "SimSun",
                  }),
                ],
                spacing: { before: 100, after: 100 },
              }),
              new Paragraph({
                text: edu.description || '',
                spacing: {
                  after: 200,
                },
              }),
            ];
          }).flat(),

          // 工作经历
          new Paragraph({
            text: '工作经历',
            heading: HeadingLevel.HEADING_1,
            thematicBreak: true,
            spacing: {
              before: 400,
            },
          }),

          ...workExperiences.map(work => {
            return [
              new Paragraph({
                text: `${work.company_name || work.company} - ${work.position}`,
                heading: HeadingLevel.HEADING_2,
              }),
              new Paragraph({
                text: `${work.start_date ? new Date(work.start_date).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' }) : ''} - ${work.end_date ? new Date(work.end_date).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' }) : '至今'}`,
                spacing: {
                  before: 100,
                  after: 100,
                },
              }),
              new Paragraph({
                text: work.description || '',
                spacing: {
                  after: 200,
                },
              }),
            ];
          }).flat(),

          // 实习经历
          ...(internships.length > 0 ? [
            new Paragraph({
              text: '实习经历',
              heading: HeadingLevel.HEADING_1,
              thematicBreak: true,
              spacing: {
                before: 400,
              },
            }),

            ...internships.map(internship => {
              return [
                new Paragraph({
                  text: `${internship.company} - ${internship.position}`,
                  heading: HeadingLevel.HEADING_2,
                }),
                new Paragraph({
                  text: internship.period || '',
                  spacing: {
                    before: 100,
                    after: 100,
                  },
                }),
                new Paragraph({
                  text: internship.description || '',
                  spacing: {
                    after: 200,
                  },
                }),
              ];
            }).flat(),
          ] : []),

          // 专业技能
          new Paragraph({
            text: '专业技能',
            heading: HeadingLevel.HEADING_1,
            thematicBreak: true,
            spacing: {
              before: 400,
            },
          }),

          ...skills.map(skill => {
            const proficiencyText = skill.proficiency === 1 ? '入门' : skill.proficiency === 2 ? '基本' : '精通';
            return new Paragraph({
              text: `${skill.name} (${proficiencyText}): ${skill.description || ''}`,
              bullet: {
                level: 0,
              },
              spacing: {
                after: 100,
              },
            });
          }),

          // 获奖情况
          ...(awards.length > 0 ? [
            new Paragraph({
              text: '获奖情况',
              heading: HeadingLevel.HEADING_1,
              thematicBreak: true,
              spacing: {
                before: 400,
              },
            }),

            ...awards.map(award => {
              return [
                new Paragraph({
                  text: `${award.name} - ${award.issuer}`,
                  heading: HeadingLevel.HEADING_2,
                }),
                new Paragraph({
                  text: award.date || '',
                  spacing: {
                    before: 100,
                    after: 100,
                  },
                }),
                new Paragraph({
                  text: award.description || '',
                  spacing: {
                    after: 200,
                  },
                }),
              ];
            }).flat(),
          ] : []),
        ],
      }],
    });

    // 生成Word文档的Buffer
    const buffer = await Packer.toBuffer(doc);

    // 设置响应头，使浏览器下载文件
    const headers = new Headers();
    headers.set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    headers.set('Content-Disposition', `attachment; filename=${encodeURIComponent(user.username)}_resume.docx`);

    return new NextResponse(buffer, {
      status: 200,
      headers,
    });

  } catch (error) {
    console.error('导出简历错误:', error);
    return NextResponse.json(
      { error: '导出简历失败，请稍后再试' },
      { status: 500 }
    );
  }
}
